package com.example.yian.controller;

import com.example.yian.entity.CaptchaEntity;
import com.example.yian.entity.ProjectInfo;
import com.example.yian.entity.TextSearchResponse;
import com.example.yian.entity.User;
import com.example.yian.mapper.CaptchaEntityMapper;
import com.example.yian.mapper.TextSearchRequestMapper;
import com.example.yian.repository.CaptchaRepository;
import com.example.yian.service.CaptchaService;
import com.example.yian.service.ProjectInfoService;
import com.example.yian.service.WeChatAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 验证码控制器，用于处理验证码相关的请求。
 */
@RestController
public class CaptchaController {

    private static final Logger log = LoggerFactory.getLogger(SecurityRiskController.class);

    private static final String CAPTCHA_KEY = "captcha";

    @Autowired
    private CaptchaRepository captchaRepository;

    @Autowired
    private CaptchaEntityMapper captchaEntityMapper;

    @Autowired
    private WeChatAuthService weChatAuthService;

    @Autowired
    private CaptchaService captchaService;
    /**
     * 校验验证码。
     * @param captchaCode 用户提交的验证码
     * @return 验证码是否正确
     */
    @PostMapping("/verifyCaptcha")
    public Map<String, Object>  verifyCaptcha(@RequestHeader("Authorization") String token, @RequestBody  Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isEmpty()) {
            log.error("verifyCaptcha | userIdOpt is empty!");
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }

        String strCode = (String) requestBody.get("code");
        if (strCode == null || strCode.length() != 4 || !strCode.matches("\\d{4}"))
        {
            log.error("verifyCaptcha | code is InValid!");
            response.put("code", 400);
            response.put("msg", "失败");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", Map.of("InvitationStatus", false));
            response.put("data", Map.of("errorCode", 1));
            return response;
        }

        // 查询数据库中是否存在该验证码
        Optional<CaptchaEntity> optionalCaptcha = Optional.ofNullable(captchaEntityMapper.selectByCode(strCode));
        if (optionalCaptcha.isPresent()) {
            CaptchaEntity captcha = optionalCaptcha.get();
            if(captcha.getBindUserId() != 0)
            {
                log.error("verifyCaptcha | code is InUsed!");
                response.put("code", 400);
                response.put("msg", "失败");
                response.put("time", Instant.now().toEpochMilli());
                response.put("data", Map.of("InvitationStatus", false));
                response.put("data", Map.of("errorCode", 2));
                return response;
            }
            // 检查验证码是否已过期
            // if (captcha.getExpirationTime().isAfter(LocalDateTime.now())){
            if(true)
            {
                response.put("code", 200);
                response.put("msg", "成功");
                response.put("time", Instant.now().toEpochMilli());
                response.put("data", Map.of("errorCode", 0));
                response.put("data", Map.of("InvitationStatus", true));

                //同时更新授权状态

                Long userId = userIdOpt.get();
                //更新验证码状态
                captchaService.updateCaptchaEntity(userId, strCode);
            } else {
                response.put("code", 400);
                response.put("msg", "失败");
                response.put("time", Instant.now().toEpochMilli());
                response.put("data", Map.of("InvitationStatus", false));
            }

        } else {
            response.put("code", 400);
            response.put("msg", "失败");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", Map.of("errorCode", 3));
            response.put("data", Map.of("InvitationStatus", false));
        }
        return response;
    }

    @PostMapping("/SpecificationAuth")
    public Map<String, Object>  verifyCaptcha(@RequestHeader("Authorization") String token/*, @RequestBody Long user_id*/) {
        Map<String, Object> response = new HashMap<>();
        Optional<Long> userIdOpt = weChatAuthService.getUserIdFromToken(token);
        if (userIdOpt.isEmpty()) {
            response.put("code", 401);
            response.put("msg", "登录过期");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
            return response;
        }

        Optional<CaptchaEntity> captchaOpt = captchaService.getCaptchaEntityByUserId(userIdOpt.get());
        if (captchaOpt.isPresent()) {
            response.put("code", 200);
            response.put("msg", "成功");
            response.put("data", true);
        } else {
            log.error("SpecificationAuth | cannot find userId by AuthCode!");
            response.put("code", 404);
            response.put("msg", "未找到用户");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        }
        return response;
    }

    public static String removeQuotes(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }

        // 去除两端的单引号或双引号
        input = input.replaceAll("^['\"]|['\"]$", "");

        return input;
    }
}